package org.shj.thread;

import java.util.concurrent.*;

/**
 * @author Shen Huang Jian
 * @date 2020-05-11 10:06
 */
public class CachedThreadPool {

    private ThreadPoolExecutor cachedThreadPool;

    public ThreadPoolExecutor getCachedThreadPool(){
        if(cachedThreadPool == null){
            synchronized (this){
                if(cachedThreadPool == null){
                    int threadNum = Runtime.getRuntime().availableProcessors() * 2;
                    cachedThreadPool = new ThreadPoolExecutor(threadNum, threadNum,
                            0, TimeUnit.SECONDS,
                            new LinkedBlockingQueue<>());
                }
            }
        }
        return cachedThreadPool;
    }

    public void shutdown(){
        try {
            cachedThreadPool.awaitTermination(5, TimeUnit.MINUTES);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
